"""
url: 3.4.8/da/d7f/tutorial_back_projection.html

basic version for Back Project demo
"""

import os

import cv2
import numpy as np
import matplotlib.pyplot as plt


def hist_and_backproj(hist_size=90):
    # hist_size = 180
    ranges = [0, 180]
    
    # 3 steps to back projection
    hist = cv2.calcHist([hue_temp], [0], mask2, [hist_size], ranges, accumulate=False)
    cv2.normalize(hist, hist, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)
    bkproj = cv2.calcBackProject([hue_temp], [0], hist, ranges, scale=1)
    
    cv2.imshow('bkproj', bkproj)
    
    # plt.plot(hist)
    # plt.show()


DIR_IMG = r'C:\_AAA\BlueNet\color_seg'

# ==========================
# load image and create mask
img_temp = cv2.imread(os.path.join(DIR_IMG, 'a-template.png'))
img_test = cv2.imread(os.path.join(DIR_IMG, 'a.jpg'))
mask = (img_temp != 255).all(axis=2, keepdims=True)  # keepdims for boardcast
mask2 = (img_temp != 255).all(axis=2)  # for calcHist
mask2 = np.array(mask2, dtype=np.uint8)


cv2.imshow('', mask*img_temp)

# ==========================
# prepare the image
hsv_temp = cv2.cvtColor(img_temp, cv2.COLOR_BGR2HSV)
hsv_test = cv2.cvtColor(img_test, cv2.COLOR_BGR2HSV)
hue_temp = np.empty(hsv_temp.shape, dtype=hsv_temp.dtype)
hue_test = np.empty(hsv_test.shape, dtype=hsv_test.dtype)
from_to = (0, 0)
cv2.mixChannels([hsv_temp], [hue_temp], from_to)
cv2.mixChannels([hsv_test], [hue_test], from_to)


# ==========================
# create trackbar
WIN_NAME = 'back project'
cv2.namedWindow(WIN_NAME)
cv2.createTrackbar('num of bins:', WIN_NAME, 2, 180, hist_and_backproj)


hist_and_backproj(2)

while True:
    k = cv2.waitKey(10) & 0xFF
    if k == 27:
        exit()




